package com.woniu.mealsService.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu.mealsService.model.Address;
import com.woniu.mealsService.mapper.AddressMapper;
import com.woniu.mealsService.service.AddressService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.user.client.UserFeignClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * <p>
 * 地址表 服务实现类
 * </p>
 *
 * @author jiang
 * @since 2024年12月09日
 */
@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements AddressService {

    @Resource
    UserFeignClient userFeignClient;


    @Override
    public void insertAddress(String addressName, String operatorId, String consignee, String consigneePhone) {
        Address address = new Address();
        address.setUserId(operatorId);
        address.setAddressName(addressName);
        address.setCreateTime(LocalDateTime.now());
        address.setUpdateTime(LocalDateTime.now());
        address.setConsignee(consignee);
        address.setConsigneePhone(consigneePhone);

        if(this.list(new QueryWrapper<Address>().eq("user_id",operatorId)).size()==0){
            address.setAddressState("0");
            this.save(address);
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            Address address1 = this.    getOne(new QueryWrapper<Address>().eq("address_name",addressName));
            userFeignClient.changeDefaultAddress(Integer.valueOf(address1.getAddressId().toString()),address.getAddressName(),Integer.valueOf(operatorId));
        }else {
            address.setAddressState("1");
            this.save(address);
        }

    }

    @Override
    public void updateAddress(String newAddressName, Integer addressId,  String consignee,  String consigneePhone) {
        Address address = this.getById(addressId);
        address.setAddressName(newAddressName);
        address.setConsigneePhone(consigneePhone);
        address.setConsignee(consignee);
        this.updateById(address);
    }

    @Override
    public void setDefaultAddress(Integer addressId, Integer userId) {
        Address address = this.getById(addressId);
        userFeignClient.changeDefaultAddress(addressId,address.getAddressName(),userId);
        address.setAddressState("0");
        this.updateById(address);
    }


}
